namespace BM.Tools.WebControls.MForm
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;        
    using System.Web.UI;
    
    using BM.Tools.WebControls.MForm.Controls;    
    using BM.Tools.WebControls.MForm.ScriptReferences;    

    /// <summary>
    /// A class that helps the <see cref="Root" /> control with registering scripts.
    /// </summary>
    public class RootScriptHelper
    {        
        /// <summary>
        /// Initializes a new instance of the <see cref="RootScriptHelper"/> class. 
        /// </summary>
        /// <param name="root">
        /// The root control.
        /// </param>
        public RootScriptHelper(Root root)
        {
            Root = root;
        }

        /// <summary>
        /// Gets the control on which the the helper works.
        /// </summary>
        /// <value>
        /// The root control.
        /// </value>
        public Root Root
        {
            get;
            private set;
        }

        /// <summary>
        /// Generates the MForm client descriptor
        /// </summary>
        /// <returns>
        /// the MForm client descriptor
        /// </returns>
        [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "The lowercase characters are needed by javascript.")]
        public ScriptDescriptor GetRootDescriptor()
        {
            var descriptor = new ScriptControlDescriptor("MForm", Root.ClientID);            
            descriptor.AddProperty("mode", Root.Mode.ToString().ToLower(CultureInfo.InvariantCulture));
            descriptor.AddProperty("shouldValidateInViewMode", Root.ShouldValidateInViewMode);
            descriptor.AddProperty("idSeparator", Root.Page.IdSeparator);
            descriptor.AddProperty("culturalContext", Root.CulturalContext);
            if (!String.IsNullOrEmpty(Root.OnClientLoadComplete))
            {
                descriptor.AddEvent("loadComplete", Root.OnClientLoadComplete);
            }

            if (!String.IsNullOrEmpty(Root.OnClientItemCreated))
            {
                descriptor.AddEvent("itemCreated", Root.OnClientItemCreated);
            }

            if (!String.IsNullOrEmpty(Root.OnClientItemRemoved))
            {
                descriptor.AddEvent("itemRemoved", Root.OnClientItemRemoved);
            }

            return descriptor;
        }

        /// <summary>
        /// Adds all resources and scripts associated with the root control.
        /// </summary>
        public void RegisterScripts()
        {
            ScriptIncluder.IncludeResources(Root);
        }
    }
}